package com.lagou.server;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class StaticResourceUtil {

    /**
     * 获取静态资源文件的绝对路径
     *
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path) {
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\", "/") + path;
    }

    /**
     * 读取静态资源文件输入流，通过输出流输出
     *
     * @param fileInputStream
     * @param outputStream
     */
    public static void outputStaticResource(FileInputStream fileInputStream, OutputStream outputStream) throws IOException {
        int available = 0;
        while (available == 0) {
            available = fileInputStream.available();
        }

        // 输出响应头
        outputStream.write(HttpProtocolUtil.getHttpHeader200(available).getBytes());

        // 读取内容并输出
        // 已经读取了的字节的长度
        long written = 0;
        // 计划每次缓冲的长度
        int byteSize = 1024;

        byte[] bytes = new byte[byteSize];

        while (written < available) {
            if (written + byteSize > available) { //说明剩余未读取大小不足一个1024长度，那么就按真实长度
                // 剩余的文件长度
                byteSize = (int) (available - written);
                bytes = new byte[byteSize];
            }

            fileInputStream.read(bytes);

            outputStream.write(bytes);

            outputStream.flush();

            written += byteSize;
        }
    }
}
